package heman.server.controllers;

import heman.server.entities.Table;
import heman.server.entities.TableManager;
import heman.server.entities.TableType;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * Options controller handles OPTIONS message.
 * <xs:element name="options">
 * 	<xs:complexType>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 		<xs:attribute name="options" type="options-string" use="optional" /> 
 * 		<xs:attribute name="seed" type="xs:integer" use="optional" /> 
 * 		<xs:attribute name="game" type="xs:string" use="optional" /> 
 * 		<xs:attribute name="type" type="tableChoice" default="private" /> 
 * 	</xs:complexType>
 * </xs:element>
 *
 * @author Yanyi Zhang
 *
 */
public class OptionsController implements IProcessServerMessage {
	public boolean process(Communicator com, Message m){
		String originator=m.getOriginator();
		NamedNodeMap map=m.contents().getAttributes();
		String tableID=map.getNamedItem("table").getNodeValue();
		Table TargetTable=TableManager.getInstance().getTable(tableID);
		String moderator=TargetTable.getModerator().getId();
		if(!moderator.equals(originator))//if the message does not come from moderator
			return false;
		if(map.getNamedItem("options")!=null){
			TargetTable.setOptions(map.getNamedItem("options").getNodeValue());
		}
		if(map.getNamedItem("seed")!=null){
			TargetTable.setSeed(Integer.parseInt(map.getNamedItem("seed").getNodeValue()));
		}
		if(map.getNamedItem("game")!=null){
			TargetTable.setGame(map.getNamedItem("game").getNodeValue());
		}
		if(map.getNamedItem("type")!=null){
			TableType type=TableType.PRIVATE;
			TargetTable.setType(type.fromString(map.getNamedItem("type").getNodeValue()));
		}
		Message r;
		StringBuilder sb = new StringBuilder(Message.responseHeader(true,m.id));
        sb.append("<tableResponse>");
        sb.append(TargetTable.toXML());
        sb.append("</tableResponse></response>");
        Document d = Message.construct(sb.toString());
        r = new Message (d);
        r.setOriginator(originator);
        r.setRecipient(originator);//respond to originator
        r.setBroadcast();//respond to others
        return com.distribute(r);
	}
}
